/**
 * 前台首页路由设置
 */

'use strict'
const express = require('express');
const router = express.Router();
const _model = require('../../models');
const moment = require('moment');


var hbs = require('hbs');
hbs.registerHelper('plus', function(num, context) {
  return num + 1
})

/**
 * 从一列数组中随机获取几个数字
 * @param arr
 * @param count
 */
function getRandNumbers(arr, count) {
  var shuffled = arr.slice(0), i = arr.length, min = i - parseInt(count), temp, index;
  while (i-- > min) {
    index = Math.floor((i + 1) * Math.random());
    temp = shuffled[index];
    shuffled[index] = shuffled[i];
    shuffled[i] = temp;
  }
  return shuffled.slice(min);
}

/**
 * 获取用户信息
 * @param options
 * @param callback
 */
function getUserInfo(options,callback) {
  _model(options.path,function (mycollection) {
    var doc = mycollection.findOne({
      user_idcard : options.user_idcard
    });
    callback && callback(doc);
  });
}

/**
 * 检测用户是否登录
 * @param req
 * @param res
 * @param next
 */
function checkUserLogin(req,res,next){
  if(req.session.user ){
    next()
  }else{

    res.format({

      json: function(){
        res.json({code: '-1', msg: '请重新登录', data: null});
      },

      html: function() {
        res.redirect('/login');
      }
    });

  }
}

/**
 * 后台入口
 */
router.get('/', function (req,res,next) {

  _model('dba/exam.json',function (mycollection) {
    var examInfo = mycollection.findOne({status:'exam'});
    if(!examInfo){
      res.render('error',{
        message: '没有找到考试信息',
        title : '错误提示'
      });
    }else{
      var _id = examInfo.exam_id;
      if(!req.session.user){
        var url = req.originalUrl;
        res.redirect('/login?url='+url+'&_id='+_id);
      }else{
        res.redirect('/exam/'+_id+'.html');
      }
    };

  });
});

router.get('/exam/alert.html',function (req,res) {
  res.send('<div class="dialog"><h1>信息提示</h1><div class="msg"></div><div class="form-group toolbar"><button class="btn btn-primary cancel" type="submit">确定</button></div></div>');
});

router.get('/exam/confirm.html',function (req,res) {
  res.send('<div class="dialog"><h1>信息确认</h1><div class="msg"></div><div class="form-group toolbar"><button class="btn btn-default cancel" type="button" data-default="Cancel">Cancel</button><button class="btn btn-primary ok" type="submit" data-default="OK">OK</button></div></div>');
});


router.get('/check_exam/alert.html',function (req,res) {
  res.send('<div class="dialog"><h1>信息提示</h1><div class="msg"></div><div class="form-group toolbar"><button class="btn btn-primary cancel" type="submit">确定</button></div></div>');
});

router.get('/check_exam/confirm.html',function (req,res) {
  res.send('<div class="dialog"><h1>信息确认</h1><div class="msg"></div><div class="form-group toolbar"><button class="btn btn-default cancel" type="button" data-default="Cancel">Cancel</button><button class="btn btn-primary ok" type="submit" data-default="OK">OK</button></div></div>');
});

/**
 * 登录页面
 */
router.get('/login', function(req, res, next){
  var url = req.query.url || '', _id = req.query._id || '';
  if ( req.session.user ) {
    res.redirect(url);
  }else{
    res.render('login',{
      error: req.flash('error'),
      _id : _id,
      url : url,
      title: '登录'
    });
  }
});

/**
 * 用户登录提交
 */
router.post('/login',function (req, res, next) {

  var url = req.body.url, _id = req.body._id;

  if(!req.body.user_name || !req.body.user_idcard){
    req.flash('error', '请输入姓名和身份证号');
    return res.redirect('/login?url='+url+'&_id='+_id);
  };

  if(!_id || _id == '/'){
    req.flash('error', '请输入正确的考试地址');
    return res.redirect('/login');
  };

  _model('dba/exam.json',function (mycollection) {
    var examInfo = mycollection.findOne({exam_id:parseInt(_id)});
    if(!examInfo){
      return res.send('没有找到考试信息');
    };
    var path = 'dba/users/user_'+examInfo.$loki+'.json';
    getUserInfo({
      path : path,
      user_idcard : req.body.user_idcard
    },function (doc) {
      if(doc){

        if(doc.user_name == req.body.user_name){
          // 是否可以查看成绩
          // if(doc.user_score){
          //   req.flash('error', '您已经参加过本场考试');
          //   return res.redirect('/login?url='+url+'&_id='+_id);
          // }
          req.session.user = doc;
          req.session.$loki = examInfo.$loki;
          req.session.exam_id = parseInt(_id);
          return res.redirect(url);
        }else{
          req.flash('error', '姓名或身份证号错误');
          return res.redirect('/login?url='+url+'&_id='+_id);
        }

      }else{
        req.flash('error', '姓名或身份证号错误');
        return res.redirect('/login?url='+url+'&_id='+_id);
      }
    })
  });

});

/**
 * 用户退出
 */
router.get('/logout',function(req,res,next) {
  let _id = req.session.exam_id;
  let url = '/exam/'+_id+'.html';
  req.session.destroy(function(err) {
    if (err) {
      next(err)
    } else {
      return res.redirect('/login?url='+url+'&_id='+_id);
    }
  })
});


router.post('/submit',function (req,res,next) {

  _model('dba/exam.json',function (mycollection) {
    var examInfo = mycollection.findOne({$loki:parseInt(req.session.$loki)});
    if(!examInfo){
      return res.json({
        msg: '没有找到该场考试的信息'
      });
    };
    var examScore = {
      'tfng' : parseInt(examInfo.exam_tfng.score),
      'single' : parseInt(examInfo.exam_single.score),
      'multiple' : parseInt(examInfo.exam_multiple.score)
    };

    var questionPath = examInfo.exam_question_path, formdata = req.body;
    var list = [].concat(req.session.user.user_questions.tfng,req.session.user.user_questions.single,req.session.user.user_questions.multiple);
    _model(questionPath,function (mycollection) {

      var str, score = 0;
      //获取问题列表
      var doc = mycollection.find({
        $loki : {
          '$in' : list
        }
      });

      doc.forEach(item=>{
        var id = item.$loki;

        if(Object.prototype.toString.call(formdata[id]) == '[object Array]'){
          str = formdata[id].join('');
        }else{
          str = formdata[id];
        };

        if(str === item.eq_answer){
          score += examScore[item['eq_type']]
        }
      });

      console.log('用户最终得分',score);

      _model(examInfo.exam_user_path,function (usercollection,db) {
        var userinfo = usercollection.findOne({$loki:req.session.user.$loki});
        if(userinfo.user_score){
          return res.json({
            msg: '您已经参加过考试,您的得分'+userinfo.user_score+',无法重复考试'
          });
        }else{
          usercollection.chain().find({$loki:req.session.user.$loki}).update(function (obj) {
            obj.user_answer = formdata;
            obj.user_score = score;
          });

          db.saveDatabase();

          return res.json({
            msg : 'logout',
            score : score
          });
        };

      });

    });

  });

})

/**
 * 记录答案信息
 */
router.post('/record',function (req,res,next) {

  _model('dba/exam.json',function (mycollection) {
    var examInfo = mycollection.findOne({$loki:parseInt(req.session.$loki)});
    if(!examInfo){
      return res.json({
        msg: '没有找到该场考试的信息'
      });
    };

    var formdata = req.body;
    _model(examInfo.exam_user_path,function (usercollection,db) {
      usercollection.chain().find({$loki:req.session.user.$loki}).update(function (obj) {
        obj.user_answer = formdata;
      });

      db.saveDatabase();
      return res.json({
        msg : 'succ'
      });

    });

  });

})

/**
 * 文章展示
 */
router.get('/exam/:_id.html', function (req,res,next) {

  _model('dba/exam.json',function (mycollection) {
    var doc = mycollection.findOne({exam_id:parseInt(req.params._id)});
    if(!doc){
      res.send('没有找到考试信息');
    }else{

      if(doc.status != 'exam'){
        return res.render('error',{
          message: '未找到正在进行的考试',
          title : '错误提示'
        });
      };
      if(!req.session.user){
        var url = req.originalUrl, _id = req.params._id;
        res.redirect('/login?url='+url+'&_id='+_id);
      }else{

        _model('dba/room.json',function (roomCollection) {
          // console.log(req.session.user);
          var roomInfo = roomCollection.findOne({$loki : req.session.user.room_id});
          if(!roomInfo){
            req.session.destroy();

            return res.render('error',{
              message: '没有找到考场信息',
              title : '错误提示'
            });
          }

          if(moment().format('YYYY-MM-DD') == roomInfo['room_date']){

            if(moment().format('HH:mm') < roomInfo['room_start_time']){
              //req.session.destroy();

              var now = moment();
              var start = moment(roomInfo['room_start_time'],'HH:mm');
              var timelimit = start.diff(now,'minutes') + 1;
              return res.render('exam-time',{
                roomInfo : roomInfo,
                timelimit : timelimit,
                message: '考试时间还没到',
                title : '错误提示'
              });
            }
            if(moment().format('HH:mm') > roomInfo['room_end_time']){
              req.session.destroy();
              return res.render('error',{
                message: '考试时间已经结束',
                title : '错误提示'
              });
            }
          }else{
            if(moment() < moment(roomInfo['room_date'])){
              req.session.destroy();
              return res.render('error',{
                message: '本场考试日期还没到',
                title : '错误提示'
              });
            }
            if(moment() > moment(roomInfo['room_date'])){
              req.session.destroy();
              return res.render('error',{
                message: '本场考试已经结束',
                title : '错误提示'
              });
            }
          }

          doc.total = doc['exam_tfng']['total'] + doc['exam_single']['total'] + doc['exam_multiple']['total'];
          var questionPath = doc.exam_question_path;

          var now = moment();
          var end = moment(roomInfo['room_end_time'],'HH:mm');
          var timelimit = end.diff(now,'minutes');

          /**
           * 如果有成绩,进入查看成绩页面
           */
          if(req.session.user.user_score !== undefined || req.session.user.user_questions){

            var exam_multiple_array = req.session.user.user_questions.multiple,
              exam_single_array = req.session.user.user_questions.single,
              exam_tfng_array = req.session.user.user_questions.tfng;

            _model(questionPath,function (mycollection) {
              var answer = req.session.user.user_answer;
              var tfng_list = mycollection.find({
                $loki : {'$in':exam_tfng_array}
              });
              var single_list = mycollection.find({
                $loki : {'$in':exam_single_array}
              });
              var multiple_list = mycollection.find({
                $loki : {'$in':exam_multiple_array}
              });

              if(req.session.user.user_score !== undefined){
                res.render('exam-score',{
                  userinfo : req.session.user,
                  examinfo : doc,
                  tfng_list : tfng_list,
                  single_list : single_list,
                  multiple_list : multiple_list,
                  user_answer : JSON.stringify(req.session.user.user_answer)
                });
              }else{
                res.render('exam',{
                  userinfo : req.session.user,
                  timelimit : timelimit,
                  examinfo : doc,
                  tfng_list : tfng_list,
                  single_list : single_list,
                  multiple_list : multiple_list
                });
              }

            });
          }else{


            if(doc.exam_qetype === "0"){
              _model(questionPath,function (mycollection) {
                var tfng_list = mycollection.find({
                  $loki : {'$in':doc.exam_tfng_array}
                });
                var single_list = mycollection.find({
                  $loki : {'$in':doc.exam_single_array}
                });
                var multiple_list = mycollection.find({
                  $loki : {'$in':doc.exam_multiple_array}
                });

                var user_questions = {
                  tfng : doc.exam_tfng_array,
                  single : doc.exam_single_array,
                  multiple : doc.exam_multiple_array
                };

                _model(doc.exam_user_path,function (usercollection,db) {
                  usercollection.chain().find({$loki:req.session.user.$loki}).update(function (obj) {
                    obj.user_questions = user_questions;
                  });
                  req.session.user.user_questions = user_questions;
                  db.saveDatabase();
                });

                res.render('exam',{
                  userinfo : req.session.user,
                  timelimit : timelimit,
                  examinfo : doc,
                  tfng_list : tfng_list,
                  single_list : single_list,
                  multiple_list : multiple_list
                });

              });
            }else{

              var exam_tfng_array = [], exam_single_array = [], exam_multiple_array = [];
              doc.exam_questions.forEach((qitems)=>{
                exam_tfng_array = exam_tfng_array.concat(getRandNumbers(qitems.tfng_list,qitems.tfng));
                exam_single_array = exam_single_array.concat(getRandNumbers(qitems.single_list,qitems.single));
                exam_multiple_array = exam_multiple_array.concat(getRandNumbers(qitems.multiple_list,qitems.multiple));
              });

              _model(questionPath,function (mycollection) {
                var tfng_list = mycollection.find({
                  $loki : {'$in':exam_tfng_array}
                });
                var single_list = mycollection.find({
                  $loki : {'$in':exam_single_array}
                });
                var multiple_list = mycollection.find({
                  $loki : {'$in':exam_multiple_array}
                });


                var user_questions = {
                  tfng : exam_tfng_array,
                  single : exam_single_array,
                  multiple : exam_multiple_array
                };

                _model(doc.exam_user_path,function (usercollection,db) {
                  usercollection.chain().find({$loki:req.session.user.$loki}).update(function (obj) {
                    obj.user_questions = user_questions;
                  });
                  req.session.user.user_questions = user_questions;
                  db.saveDatabase();
                });

                res.render('exam',{
                  userinfo : req.session.user,
                  timelimit : timelimit,
                  examinfo : doc,
                  tfng_list : tfng_list,
                  single_list : single_list,
                  multiple_list : multiple_list
                });

              });

            }

          }

        });

      }
    }
  });
});

/**
 * 试卷
 */
router.get('/check_exam/:_id.html', function (req,res,next) {
  req.session.destroy();
  const userinfo = {
    "user_name":"测试员",
    "user_idcard":"1",
    "user_area":"说的"
  };

  _model('dba/exam.json',function (mycollection) {
    var doc = mycollection.findOne({exam_id:parseInt(req.params._id)});
    if(!doc){
      res.send('没有找到考试信息');
    }else{

      _model('dba/room.json',function (roomCollection) {

        doc.total = doc['exam_tfng']['total'] + doc['exam_single']['total'] + doc['exam_multiple']['total'];
        var questionPath = doc.exam_question_path;
        var timelimit = 120;

        if(doc.exam_qetype === "0"){
          _model(questionPath,function (mycollection) {
            var tfng_list = mycollection.find({
              $loki : {'$in':doc.exam_tfng_array}
            });
            var single_list = mycollection.find({
              $loki : {'$in':doc.exam_single_array}
            });
            var multiple_list = mycollection.find({
              $loki : {'$in':doc.exam_multiple_array}
            });

            res.render('exam-check',{
              userinfo : userinfo,
              timelimit : timelimit,
              examinfo : doc,
              tfng_list : tfng_list,
              single_list : single_list,
              multiple_list : multiple_list
            });

          });
        }else{

          var exam_tfng_array = [], exam_single_array = [], exam_multiple_array = [];
          doc.exam_questions.forEach((qitems)=>{
            exam_tfng_array = exam_tfng_array.concat(getRandNumbers(qitems.tfng_list,qitems.tfng));
            exam_single_array = exam_single_array.concat(getRandNumbers(qitems.single_list,qitems.single));
            exam_multiple_array = exam_multiple_array.concat(getRandNumbers(qitems.multiple_list,qitems.multiple));
          });

          _model(questionPath,function (mycollection) {
            var tfng_list = mycollection.find({
              $loki : {'$in':exam_tfng_array}
            });
            var single_list = mycollection.find({
              $loki : {'$in':exam_single_array}
            });
            var multiple_list = mycollection.find({
              $loki : {'$in':exam_multiple_array}
            });

            res.render('exam-check',{
              userinfo : userinfo,
              timelimit : timelimit,
              examinfo : doc,
              tfng_list : tfng_list,
              single_list : single_list,
              multiple_list : multiple_list
            });

          });

        }

      });

    }
  });
});

module.exports = router;